﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace SmartDeviceProject9
{
    public partial class MaterialInventoryForm : Form
    {
        public MaterialInventoryForm()
        {
            InitializeComponent();
        }
        public Form ParentForm { get; set; }

        private bool closeNoEnsure = true;
        private void MaterialInventory_Closing(object sender, CancelEventArgs e)
        {

            if (closeNoEnsure)
            {
                if (MessageBox.Show("关闭后，当前数据将丢失，是否继续？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.None, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    return;
                }
                else
                {
                    closeNoEnsure = false;
                    this.Close();

                }
            }
            else
            {

                e.Cancel = false;
            }
            ParentForm.Show();
        }

        private DataTable bindDataSource;
        private DataTable DataGrid2Table;    //基本信息
        private DataTable ResultsTable;      //条码信息缓存
        private DataTable SubResulteTale;    //条码缓存子单据体
        private string ID;                  //缓存单据Id\
        private DataSet dataS=new DataSet(); //保存用;



        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MaterialInventoryForm_Load(object sender, EventArgs e)
        {
            Type type = typeof(string);

            #region 条码缓存列设置
            //单据体
            ResultsTable=new DataTable();
            ResultsTable.Columns.Add(new DataColumn("ID", type));              //Id
            //ResultsTable.Columns.Add(new DataColumn("FBarCode", type));        // 条码
            ResultsTable.Columns.Add(new DataColumn("FMaterialName",type));    //物料名
            ResultsTable.Columns.Add(new DataColumn("FMaterialNum",type));     //物料编码
            ResultsTable.Columns.Add(new DataColumn("FMaterialId", type));     //物料Id
            ResultsTable.Columns.Add(new DataColumn("FAcctQty", type));         //账存数
            ResultsTable.Columns.Add(new DataColumn("AuxpropNum",type));        //幅宽
            ResultsTable.Columns.Add(new DataColumn("AuxpropValue", type));       //幅宽值
            ResultsTable.Columns.Add(new DataColumn("FDiameter", type));         //芯径
            ResultsTable.Columns.Add(new DataColumn("FDensity",type));           //密度
            ResultsTable.Columns.Add(new DataColumn("FUnit", type));              //单位
            ResultsTable.Columns.Add(new DataColumn("FCountQty", type));          //盘点数
            dataS.Tables.Add(ResultsTable);
            //子单据体
            SubResulteTale = new DataTable();
            SubResulteTale.Columns.Add(new DataColumn("ID", type));
            SubResulteTale.Columns.Add(new DataColumn("FID", type));
            SubResulteTale.Columns.Add(new DataColumn("F_D_BarCode", type));
            SubResulteTale.Columns.Add(new DataColumn("FMaterialName", type));
            SubResulteTale.Columns.Add(new DataColumn("FMaterialNum", type));
            SubResulteTale.Columns.Add(new DataColumn("AuxpropNum", type));         //幅宽
            SubResulteTale.Columns.Add(new DataColumn("AuxpropValue",type));        //幅宽值
            SubResulteTale.Columns.Add(new DataColumn("FDiameter", type));         //芯径
            SubResulteTale.Columns.Add(new DataColumn("FDensity", type));           //密度
            SubResulteTale.Columns.Add(new DataColumn("F_D_UnitID", type));         //单位
            SubResulteTale.Columns.Add(new DataColumn("F_D_Qty", type));            //账存数
            SubResulteTale.Columns.Add(new DataColumn("F_D_CountQty", type));       //盘点数
            dataS.Tables.Add(SubResulteTale);

            #endregion


            bindDataSource = new DataTable();
            bindDataSource.Columns.Add(new DataColumn("条码", type));
            bindDataSource.Columns.Add(new DataColumn("原纸名称", type));
            bindDataSource.Columns.Add(new DataColumn("幅宽", type));
            bindDataSource.Columns.Add(new DataColumn("账存数", type));
            bindDataSource.Columns.Add(new DataColumn("盘点数", type));
            this.dataGrid1.DataSource = bindDataSource;
            //dataGrid1.


            DataGrid2Table = new DataTable();
            DataGrid2Table.TableName = "盘点作业列表";
            DataGrid2Table.Columns.Add(new DataColumn("ID", type));
            DataGrid2Table.Columns.Add(new DataColumn("盘点作业编号", type));
            DataGrid2Table.Columns.Add(new DataColumn("账存日期", type));
            DataGrid2Table.Columns.Add(new DataColumn("备注", type));
            this.dataGrid2.DataSource = DataGrid2Table;
            DataGridTableStyle t=new DataGridTableStyle();
            DataGridTextBoxColumn c = new DataGridTextBoxColumn();
            c.Width = 0;
            c.HeaderText = "ID";
            c.MappingName = "ID";
            DataGridTextBoxColumn c1 = new DataGridTextBoxColumn();
            c1.Width = 80;
            c1.HeaderText = "盘点作业编号";
            c1.MappingName = "盘点作业编号";
            DataGridTextBoxColumn c2 = new DataGridTextBoxColumn();
            c2.Width = 50;
            c2.HeaderText = "账存日期";
            c2.MappingName = "账存日期";
            DataGridTextBoxColumn c3 = new DataGridTextBoxColumn();
            c3.Width = 80;
            c3.HeaderText = "备注";
            c3.MappingName = "备注";

            t.GridColumnStyles.Add(c);
            t.GridColumnStyles.Add(c1);
            t.GridColumnStyles.Add(c2);
            t.GridColumnStyles.Add(c3);


            t.MappingName = "盘点作业列表";
            this.dataGrid2.TableStyles.Add(t);


            DataTable table = new DataTable();
            table.Columns.Add("OrgId", type);
            table.Columns.Add("Name", type);
            int selectIndex = -1;
            foreach (var org in Context.Orgs)
            {
                if (org.Value.OrgId == Context.UserCurrentOrgId)
                {
                    selectIndex = 0;
                    DataRow row = table.NewRow();
                    row["OrgId"] = org.Value.OrgId;
                    row["Name"] = org.Value.Name;
                    table.Rows.Add(row);
                }
            }
            if (selectIndex >= 0)
            {
                this.cbxCheckOrg.DataSource = table;
                cbxCheckOrg.DisplayMember = "Name";
                cbxCheckOrg.ValueMember = "OrgId";
                cbxCheckOrg.SelectedIndex = selectIndex;
                cbxCheckOrg_SelectedIndexChanged(null, null);
            }
        }
        private string checkNum;
        private void tbxCheckNum_LostFocus(object sender, EventArgs e)
        {
            string org = cbxCheckOrg.SelectedValue as string;
            checkNum=tbxCheckNum.Text.Trim();
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 组织设置仓库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxCheckOrg_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataGrid2Table.Rows.Clear();
            this.tbxCheckNum.Text = string.Empty;

            //清空缓存
            ResultsTable.Rows.Clear();
            SubResulteTale.Rows.Clear();
            bindDataSource.Rows.Clear();


            Type type = typeof(string);
            string org = cbxCheckOrg.SelectedValue as string;
            if (org != null && org != "")
            {
                DataTable table = new DataTable();
                table.Columns.Add("StkId", type);
                table.Columns.Add("name", type);
                List<Stk> listStk = Context.Orgs[org]._stks;

                foreach (Stk s in listStk)
                {
                    DataRow dr = table.NewRow();
                    dr["StkId"] = s.StkId;
                    dr["name"] = s.Name;
                    table.Rows.Add(dr);

                }
                if (table.Rows.Count>0) 
                {
                    cbxCheckWH.DataSource = table;
                    cbxCheckWH.DisplayMember = "name";
                    cbxCheckWH.ValueMember = "StkId";
                    cbxCheckWH.SelectedIndex =0;
                    cbxCheckWH_SelectedIndexChanged(null, null);
                }
                

            }
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tbxCode_TextChanged(object sender, EventArgs e)
        {
            
        }

        /// <summary>
        /// 条码回车
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbxCode_KeyUp(object sender, KeyEventArgs e)
        {

            #region 条码回车事件

            if (e.KeyCode == Keys.Enter)
            {
                this.tbxDiameter.Focus();

            }

            #endregion
            
        }
         
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItem1_Click(object sender, EventArgs e)
        {
            if (ResultsTable.Rows.Count <= 0)
            {
                MessageBox.Show("保存失败,至少录入一条条码");
                return;
            }
            string messStr= Context.Service.InventorySave(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, ID, dataS);
            ID = string.Empty;
            this.tbxCheckNum.Text = string.Empty;
            dataS.Tables[0].Rows.Clear();   //单据体
            dataS.Tables[1].Rows.Clear();   //子单据体
           (dataGrid1.DataSource as DataTable).Rows.Clear();
           MessageBox.Show(messStr);

        }


        private void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
        {

            
        }

        
        //仓库
        private void cbxCheckWH_SelectedIndexChanged(object sender, EventArgs e)
        {
            //清空编号，
            DataGrid2Table.Rows.Clear();
            this.tbxCheckNum.Text =string.Empty;
            //清空缓存
            ResultsTable.Rows.Clear();
            SubResulteTale.Rows.Clear();
            bindDataSource.Rows.Clear();


            string stkId = this.cbxCheckWH.SelectedValue as string;
            string orgId = this.cbxCheckOrg.SelectedValue as string;
            if (stkId != null && stkId != "" && orgId !=null &&orgId !="")
            {
                DataSet DS = Context.Service.GetInventoryBill(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, orgId, stkId);
                if (DS != null)
                {
                    foreach (DataRow dr in DS.Tables[0].Rows)
                    {
                        DataRow d = DataGrid2Table.NewRow();
                        d["ID"] = dr["ID"];
                        d["盘点作业编号"] = dr["FBillNo"];
                        d["账存日期"] = dr["FBackUpDate"];
                        d["备注"] = dr["FNoteHead"];
                        DataGrid2Table.Rows.Add(d);
                    }
                }
                

            }
        }

        private void dataGrid2_Click(object sender, EventArgs e)
        {
            
        }
        /// <summary>
        /// 基础信息页签单据体双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGrid2_DoubleClick(object sender, EventArgs e)
        {




            //清空编号，
            this.tbxCheckNum.Text =string.Empty;
            bindDataSource.Rows.Clear();
           
            //清空缓存
            ResultsTable.Rows.Clear();
            SubResulteTale.Rows.Clear();

            if (this.dataGrid2.Controls.Count > 0)
            {
                
                int index = this.dataGrid2.CurrentRowIndex;
                ID = this.DataGrid2Table.Rows[index]["ID"] as string;
                string num = this.DataGrid2Table.Rows[index]["盘点作业编号"] as string;
                DataSet DS = Context.Service.InquiryBillNo(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, num);
                if (DS != null)
                {
                    string str =string.Empty;
                    //单据体缓存
                    foreach (DataRow dr in DS.Tables[0].Rows)
                    {
                        
                        #region 数据缓存

                        DataRow resRow = ResultsTable.NewRow();
                        resRow["ID"] = dr["ID"];
                        // resRow["FBarCode"] = dr["FBarCode"];                     // 条码
                        resRow["FMaterialName"] = dr["FMaterialName"];           //物料名
                        resRow["FMaterialNum"] = dr["FMaterialNum"];             //物料编码 
                        resRow["FAcctQty"] = dr["FAcctQty"];                     //账存数
                        resRow["AuxpropNum"] = dr["AuxpropNum"];                 //幅宽
                        resRow["AuxpropValue"] = dr["AuxpropValue"];                //幅宽值
                        resRow["FDiameter"] = dr["FDiameter"];                   //芯径
                        resRow["FDensity"] = dr["FDensity"];                     //密度
                        resRow["FUnit"] = dr["FUnit"];                           //单位
                        str=Convert.ToString(dr["FCountQty"]);
                        if(str==null||str=="")
                        {
                            resRow["FCountQty"] = dr["FAcctQty"];                    //盘点数     
                        }
                        else
                        {
                             resRow["FCountQty"]=dr["FCountQty"];
                        }
                        
                        ResultsTable.Rows.Add(resRow);

                        #endregion

                    }
                    
                    //子单据体缓存
                    foreach (DataRow dr in DS.Tables[1].Rows)
                    {
                        //设置条码页签
                        DataRow row = bindDataSource.NewRow();
                        row["条码"] = dr["F_D_BarCode"];
                        row["原纸名称"] = dr["FMaterialName"];
                        row["幅宽"] = dr["AuxpropNum"];
                        row["账存数"] = dr["F_D_Qty"];
                        str=Convert.ToString(dr["F_D_CountQty"]);
                        if(str==null|| str=="" || str=="0")
                        {
                            row["盘点数"] =Convert.ToDecimal( dr["F_D_Qty"]).ToString("0.##"); 
                        }
                        else
                        {
                            row["盘点数"] = Convert.ToDecimal(dr["F_D_CountQty"]).ToString("0.##"); 
                        }
                        bindDataSource.Rows.Add(row);

                        #region 缓存子单据体

                        DataRow subRow = SubResulteTale.NewRow();
                        subRow["ID"] = dr["ID"];
                        subRow["FID"] = dr["FID"];
                        subRow["F_D_BarCode"] = dr["F_D_BarCode"];
                        subRow["FMaterialName"] = dr["FMaterialName"];
                        subRow["FMaterialNum"] = dr["FMaterialNum"];
                        subRow["AuxpropNum"] = dr["AuxpropNum"];
                        subRow["AuxpropValue"] = dr["AuxpropValue"];
                        subRow["FDiameter"] = dr["FDiameter"];                   //芯径
                        subRow["FDensity"] = dr["FDensity"];                     //密度
                        subRow["F_D_UnitID"] = dr["F_D_UnitID"];
                        subRow["F_D_Qty"] = dr["F_D_Qty"];
                        if (str == null || str == "")
                        {
                            subRow["F_D_CountQty"] = dr["F_D_Qty"];
                        }
                        else
                        {
                            subRow["F_D_CountQty"] = dr["F_D_CountQty"];
                        }

                        SubResulteTale.Rows.Add(subRow);
                        #endregion

                    }
                    this.tbxCheckNum.Text = num;
                }
            }
        }

        private void dataGrid2_CurrentCellChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 确定点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string checkNum = this.tbxCheckNum.Text.Trim();    //盘点单号
            if (string.IsNullOrEmpty(checkNum) || checkNum == "")
            {
                MessageBox.Show("请先选择单据");
                this.tbxCode.Text = string.Empty;
                this.tbxDiameter.Text = string.Empty;
                return;
            }
            string s = this.tbxCode.Text.Trim();        //条码
            string tbxD = this.tbxDiameter.Text.Trim();         //直径
            this.tbxCode.Text = string.Empty;
            this.tbxDiameter.Text = string.Empty;
            this.tbxCode.Focus();
            if (string.IsNullOrEmpty(s) || s == "")
                return;
            
            int i = 0;
            decimal r2 = 0;                        //芯径
            decimal r3 = 0;                      //密度
            decimal r4 = 0;                        //幅宽
            string countQty;
            decimal r1 = tbxD != null && tbxD != "" ? Convert.ToDecimal(tbxD) : -1;        //直径

            #region 判断在不在缓存

            foreach (DataRow dsb in SubResulteTale.Rows)
            {
                if (Convert.ToString(dsb["F_D_BarCode"]) == s)
                {
                    r2 = !(dsb["FDiameter"] is DBNull) ? Convert.ToDecimal(dsb["FDiameter"]) : 0;
                    r3 = !(dsb["FDensity"] is DBNull) ? Convert.ToDecimal(dsb["FDensity"]) : 0;
                    r4 = !(dsb["AuxpropValue"] is DBNull) ? Convert.ToDecimal(dsb["AuxpropValue"]) : 0;
                    countQty = r1 >= 0 ? Weight(r1, r2, r3, r4) : Convert.ToString(dsb["F_D_Qty"]);      //盘点数    -1等于账存数

                    if (Convert.ToDecimal(countQty) < 0)
                    {
                        MessageBox.Show("退料数量不可小于0");
                        continue;
                    }

                    SubResulteTale.Rows[i]["F_D_CountQty"] = countQty;
                    bindDataSource.Rows[i]["盘点数"] = countQty;
                    return;
                }
                i++;
            }

            #endregion


            string orgId = this.cbxCheckOrg.SelectedValue as string;
            string stockId = this.cbxCheckWH.SelectedValue as string;


            //  物料编码           物料名        条码      基础数量     基础单位       幅宽        芯径            密度
            //FMaterialId,  FMaterialId.Name, FBarCode,  FBaseQty,  FBaseUnitId,    FAuxPropId  ,FDiameter   ,   FDensity   
            DataSet dataSet = Context.Service.GetCodeDetail(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, s,orgId,stockId,true);
            if (dataSet != null)
            {
                //bool _bool = true;
                DataTable table = dataSet.Tables[0];
                foreach (DataRow dr in table.Rows)
                {
                    r2 = !(dr["FDiameter"] is DBNull ) ? Convert.ToDecimal (dr["FDiameter"]) : 0;
                    r3 = !(dr["FDensity"] is DBNull ) ? Convert.ToDecimal (dr["FDensity"]): 0;
                    r4 = !(dr["AuxpropValue"] is DBNull ) ? Convert.ToDecimal (dr["AuxpropValue"]) : 0;
                    countQty = r1 >= 0 ? Weight(r1, r2, r3, r4) : Convert.ToString(dr["FBaseQty"]);      //盘点数

                    if (Convert.ToDecimal(countQty) < 0)
                    {
                        MessageBox.Show("退料数量不可小于0");
                        continue;
                    }

                    string Mat = Convert.ToString(dr["FMaterialId"]);        //物料编码
                    string FK = Convert.ToString(dr["FAuxPropId"]);             //幅宽


                   // _bool = true;
                    
                    foreach (DataRow resDr in ResultsTable.Rows)
                    {
                        if (Convert.ToString(resDr["FMaterialNum"]) == Mat && Convert.ToString(resDr["AuxpropNum"]) == FK)
                        {
                            DataRow nrow = bindDataSource.NewRow();
                            nrow["条码"] = dr["FBarCode"];
                            nrow["原纸名称"] = dr["FMaterialFName"];
                            nrow["幅宽"] = FK;
                            nrow["账存数"] = Convert.ToDecimal(dr["FBaseQty"]).ToString("0.##");
                            nrow["盘点数"] = Convert.ToDecimal(countQty).ToString("0.##");                       //盘点数默认等于账存数
                            bindDataSource.Rows.Add(nrow);



                            #region 子单据体缓存

                            DataRow subRow = SubResulteTale.NewRow();
                            subRow["ID"] = 0;
                            subRow["FID"] = 0;
                            subRow["F_D_BarCode"] = dr["FBarCode"];                     //条码
                            subRow["FMaterialName"] = dr["FMaterialFName"];             //物料名
                            subRow["FMaterialNum"] = Mat;                                 //物料编号
                            subRow["AuxpropNum"] = FK;                    //幅宽
                            subRow["AuxpropValue"] = dr["AuxpropValue"];                //幅宽值
                            subRow["F_D_UnitID"] = dr["FBaseUnitId"];                   //单位
                            subRow["F_D_Qty"] = dr["FBaseQty"];                         //账存数   等于  条码主档 的库存数    后期修改，只是字段名没变
                            subRow["F_D_CountQty"] = countQty;                          //盘点数
                            subRow["FDiameter"] = dr["FDiameter"];                     //芯径
                            subRow["FDensity"] = dr["FDensity"];                       //密度

                            SubResulteTale.Rows.Add(subRow);

                            #endregion
                        }
                    }

                    //if (_bool)
                    //{
                    //    //单据体 缓存
                    //    DataRow drRow = ResultsTable.NewRow();
                    //    drRow["ID"] = "0";
                    //    drRow["FMaterialNum"] = dr["FMaterialId"];         //物料编码
                    //    drRow["FMaterialName"] = dr["FMaterialFName"];    //物料名
                    //    //drRow["FMaterialName"] = dr[""];
                    //    //drRow["FBarCode"] = dr["FBarCode"];               //条码
                    //    //drRow["FAcctQty"] = dr["FBaseQty"];               //账存数
                    //    drRow["FUnit"] = dr["FBaseUnitId"];               //单位
                    //    drRow["AuxpropNum"] = dr["FAuxPropId"];           //幅宽
                    //    drRow["AuxpropValue"] = dr["AuxpropValue"];        //幅宽值
                    //    drRow["FDiameter"] = dr["FDiameter"];             //芯径
                    //    drRow["FDensity"] = dr["FDensity"];               //密度
                    //    //drRow["FCountQty"] = countQty;                    //盘点数      （盘点数默认等账存数）
                    //    ResultsTable.Rows.Add(drRow);
                    //}

                }
            }
            else
            {
                MessageBox.Show("未查到相关条码信息");
            }

        }
        /// <summary>
        /// 计算重量
        /// </summary>
        /// <param name="diameter">纸直径</param>
        /// <param name="coreDiameter">芯径(半径)(CM)</param>
        /// <param name="density">密度(Kg/立方米)</param>
        /// <param name="auxprop">幅宽</param>
        /// <returns>重量（）</returns>
        private string Weight(decimal diameter, decimal coreDiameter, decimal density, decimal auxprop)
        {
            decimal pi=3.1415926M;
            diameter = diameter / 2000;           //纸直径
            coreDiameter = coreDiameter / 1000;   //芯径（半径）
            auxprop = auxprop / 1000;             //幅宽
            decimal m = density * pi * (diameter * diameter - coreDiameter * coreDiameter) * auxprop;
            return Convert.ToString(m);
        }

        private void dataGrid1_DoubleClick(object sender, EventArgs e)
        {
            this.tbxCode.Text = string.Empty;
            if (this.dataGrid1.Controls.Count > 0)
            {
                int index = this.dataGrid1.CurrentRowIndex;
                string codeNum = this.bindDataSource.Rows[index]["条码"] as string;
                this.tbxCode.Text = codeNum;
                this.tbxDiameter.Focus();
            }

        }

        private void tbxDiameter_LostFocus(object sender, EventArgs e)
        {
            try
            {
                string tbx=this.tbxDiameter.Text.Trim();
                if(tbx!=null&&tbx!="")
                    Convert.ToDecimal(this.tbxDiameter.Text);
            }
            catch
            {
                this.tbxDiameter.Text = string.Empty;
                MessageBox.Show("请输入合法的数字");
            }
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void label2_ParentChanged(object sender, EventArgs e)
        {

        }

        private void tbxDiameter_TextChanged(object sender, EventArgs e)
        {

        }


    }
}